<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\services\activity\coupon;

use app\model\activity\coupon\StoreCouponProduct;
use app\services\BaseServices;
use app\dao\activity\coupon\StoreCouponProductDao;

/**
 *
 * Class StoreCouponProductServices
 * @package app\services\coupon
 * @method saveAll(array $data) 批量保存
 */
class StoreCouponProductServices extends BaseServices
{

    /**
     * StoreCouponProductServices constructor.
     * @param StoreCouponProductDao $dao
     */
    public function __construct(StoreCouponProductDao $dao)
    {
        $this->dao = $dao;
    }

    public function syncRelation($coupon_id,$products)
    {
        // 获取当前优惠券关联的所有商品ID和商品属性值ID
        $existingProducts = StoreCouponProduct::where('coupon_id', $coupon_id)
            ->column('product_id, product_attr_value_unique');

        // 构建需要删除的记录
        $idsToDelete = [];
        foreach ($existingProducts as $existingProduct) {
            $found = false;
            foreach ($products as $product) {
                if ($product['product_id'] == $existingProduct['product_id'] && $product['product_attr_value_unique'] == $existingProduct['product_attr_value_unique']) {
                    $found = true;
                    break;
                }
            }
            if (!$found) {
                $idsToDelete[] = $existingProduct['product_id']; // 存储需要删除的产品ID
            }
        }

        // 删除不需要的记录
        StoreCouponProduct::where('coupon_id', $coupon_id)
            ->whereIn('product_id', $idsToDelete)
            ->delete();

        // 获取product_ids 数组
        $product_attr_value_uniques = array_column($existingProducts, 'product_attr_value_unique');

        // 新增缺失的记录
        foreach ($products as $product) {
            $productId = $product['product_id'];
            $productAttrValueId = $product['product_attr_value_unique'];
            if (empty($product_attr_value_uniques) || !in_array($productAttrValueId, $product_attr_value_uniques)) {
                StoreCouponProduct::create([
                    'coupon_id' => $coupon_id,
                    'product_id' => $productId,
                    'product_attr_value_unique' => $productAttrValueId,
                ]);
            }
        }
    }


}
